package weibo;

import user.UserSession;
import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "SendWeiboServlet")
public class SendWeiboServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String email = UserSession.getUserSessionEmail(session);

        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(220, "not_login"));
            return;
        }

        String content = request.getParameter("content");


        String reBlog = request.getParameter("reblog_id");
        if (reBlog != null && reBlog.isEmpty()){
            if (content == null || content.isEmpty()){
                out.println(JsonOut.error(201, "no_content"));
                return;
            }
            // 先判断reBlog这个id存不存在
            if (!(new MysqlUtils()).isWeiboExist(reBlog)){
                out.println(JsonOut.error(202, "reblog_not_exist"));
                return;
            }
        }

        String image = request.getParameter("image");
        if (image == null || image.isEmpty()){
            if (content == null || content.isEmpty()){
                out.println(JsonOut.error(201, "no_content"));
                return;
            }
        }

        if (content != null && !content.isEmpty()){
            String[] fbsArr = { "\\", "\"", "'", "<", ">" };
            for (String key : fbsArr) {
                if (content.contains(key)) {
                    content = content.replace(key, "\\" + key);
                }
            }
        }

        if (!(new MysqlUtils()).sendWeibo(email, content, reBlog, image)){
            out.println(JsonOut.error(500, "sql_sth_wrong"));
            return;
        }

        out.println(JsonOut.error(0, "post_weibo_success"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
